import React, { useEffect, useState } from "react";
import { 
  StyleSheet, 
  Text, 
  View, 
  FlatList,
  TouchableOpacity,
  ActivityIndicator,
  RefreshControl
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
import { Search, Filter, SortAsc, SortDesc } from "lucide-react-native";
import { colors } from "@/constants/colors";
import { ContentListItem } from "@/components/ContentListItem";
import { useContentStore } from "@/store/content-store";
import { EnglishContent } from "@/types";
import { ScrollView } from "react-native";

export default function PlaylistScreen() {
  const router = useRouter();
  const { contents, favorites, fetchContents, toggleFavorite, addToRecentlyPlayed } = useContentStore();
  const [refreshing, setRefreshing] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterType, setFilterType] = useState<string | null>(null);
  const [filterDifficulty, setFilterDifficulty] = useState<string | null>(null);
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");

  useEffect(() => {
    fetchContents();
  }, []);

  const onRefresh = async () => {
    setRefreshing(true);
    await fetchContents();
    setRefreshing(false);
  };

  const handleContentPress = (content: EnglishContent) => {
    addToRecentlyPlayed(content.id);
    router.push(`/content/${content.id}`);
  };

  const handleContentDoubleTap = (content: EnglishContent) => {
    // In a real app, this would play the audio
    console.log(`Playing audio for ${content.title}`);
    addToRecentlyPlayed(content.id);
  };

  // Filter and sort content
  const filteredContent = contents.filter(content => {
    // Search filter
    const matchesSearch = searchQuery
      ? content.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        content.english.toLowerCase().includes(searchQuery.toLowerCase()) ||
        content.chinese.toLowerCase().includes(searchQuery.toLowerCase())
      : true;

    // Type filter
    const matchesType = filterType ? content.type === filterType : true;

    // Difficulty filter
    const matchesDifficulty = filterDifficulty ? content.difficulty === filterDifficulty : true;

    return matchesSearch && matchesType && matchesDifficulty;
  });

  // Sort content
  const sortedContent = [...filteredContent].sort((a, b) => {
    if (sortOrder === "asc") {
      return a.title.localeCompare(b.title);
    } else {
      return b.title.localeCompare(a.title);
    }
  });

  // Get unique content types and difficulties for filters
  const contentTypes = Array.from(new Set(contents.map(content => content.type)));
  const contentDifficulties = Array.from(new Set(contents.map(content => content.difficulty)));

  return (
    <SafeAreaView style={styles.container} edges={["top"]}>
      <View style={styles.header}>
        <Text style={styles.title}>English Content</Text>
        <View style={styles.searchContainer}>
          <Search size={20} color={colors.text.tertiary} style={styles.searchIcon} />
          <TouchableOpacity 
            style={styles.filterButton}
            onPress={() => setSortOrder(sortOrder === "asc" ? "desc" : "asc")}
          >
            {sortOrder === "asc" ? (
              <SortAsc size={20} color={colors.text.primary} />
            ) : (
              <SortDesc size={20} color={colors.text.primary} />
            )}
          </TouchableOpacity>
          <TouchableOpacity style={styles.filterButton}>
            <Filter size={20} color={colors.text.primary} />
          </TouchableOpacity>
        </View>
      </View>

      {/* Filter chips */}
      <View style={styles.filterChips}>
        <Text style={styles.filterLabel}>Type:</Text>
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          <TouchableOpacity
            style={[
              styles.filterChip,
              filterType === null && styles.activeFilterChip,
            ]}
            onPress={() => setFilterType(null)}
          >
            <Text
              style={[
                styles.filterChipText,
                filterType === null && styles.activeFilterChipText,
              ]}
            >
              All
            </Text>
          </TouchableOpacity>
          {contentTypes.map((type) => (
            <TouchableOpacity
              key={type}
              style={[
                styles.filterChip,
                filterType === type && styles.activeFilterChip,
              ]}
              onPress={() => setFilterType(type === filterType ? null : type)}
            >
              <Text
                style={[
                  styles.filterChipText,
                  filterType === type && styles.activeFilterChipText,
                ]}
              >
                {type}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      <View style={styles.filterChips}>
        <Text style={styles.filterLabel}>Level:</Text>
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          <TouchableOpacity
            style={[
              styles.filterChip,
              filterDifficulty === null && styles.activeFilterChip,
            ]}
            onPress={() => setFilterDifficulty(null)}
          >
            <Text
              style={[
                styles.filterChipText,
                filterDifficulty === null && styles.activeFilterChipText,
              ]}
            >
              All
            </Text>
          </TouchableOpacity>
          {contentDifficulties.map((difficulty) => (
            <TouchableOpacity
              key={difficulty}
              style={[
                styles.filterChip,
                filterDifficulty === difficulty && styles.activeFilterChip,
              ]}
              onPress={() => setFilterDifficulty(difficulty === filterDifficulty ? null : difficulty)}
            >
              <Text
                style={[
                  styles.filterChipText,
                  filterDifficulty === difficulty && styles.activeFilterChipText,
                ]}
              >
                {difficulty}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      {contents.length === 0 && !refreshing ? (
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyText}>No content available</Text>
        </View>
      ) : (
        <FlatList
          data={sortedContent}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => (
            <ContentListItem
              content={item}
              onPress={handleContentPress}
              onDoubleTap={handleContentDoubleTap}
              isFavorite={favorites.includes(item.id)}
              onToggleFavorite={toggleFavorite}
            />
          )}
          contentContainerStyle={styles.listContent}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
          }
          ListEmptyComponent={
            <View style={styles.emptyContainer}>
              <Text style={styles.emptyText}>No matching content found</Text>
            </View>
          }
        />
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    padding: 16,
    paddingBottom: 8,
  },
  title: {
    fontSize: 24,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 16,
  },
  searchContainer: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: colors.card,
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    color: colors.text.primary,
  },
  filterButton: {
    marginLeft: 12,
    padding: 4,
  },
  filterChips: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  filterLabel: {
    fontSize: 14,
    fontWeight: "500",
    color: colors.text.secondary,
    marginRight: 8,
  },
  scrollContainer: {
    flexDirection: "row",
  },
  filterChip: {
    backgroundColor: colors.card,
    borderRadius: 16,
    paddingHorizontal: 12,
    paddingVertical: 6,
    marginRight: 8,
  },
  activeFilterChip: {
    backgroundColor: colors.primary,
  },
  filterChipText: {
    fontSize: 12,
    color: colors.text.secondary,
  },
  activeFilterChipText: {
    color: colors.text.inverse,
    fontWeight: "500",
  },
  listContent: {
    padding: 16,
    paddingBottom: 100, // Add extra padding at the bottom to prevent content from being hidden by the tab bar
  },
  emptyContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 24,
  },
  emptyText: {
    fontSize: 16,
    color: colors.text.tertiary,
    textAlign: "center",
  },
});